<template>
  <div class="job-list">
    <el-card class="box-card">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm" ref="searchForm">
          <el-form-item label="职位名称" prop="jobName">
            <el-input v-model="searchForm.jobName" placeholder="请输入职位名称"></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="searchForm.remark" placeholder="请输入备注信息"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
            <el-button type="success" @click="handleAdd">新增职位</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <el-table :data="tableData" v-loading="loading" border style="width: 100%">
        <el-table-column prop="jobName" label="职位名称"></el-table-column>
        <el-table-column prop="categoryName" label="职位类别"></el-table-column>
        <el-table-column prop="demandNumber" label="需求人数"></el-table-column>
        <el-table-column prop="hiredNumber" label="已录用人数"></el-table-column>
        <el-table-column prop="remark" label="备注" show-overflow-tooltip></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" style="color: #F56C6C" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>

      <!-- 新增/编辑对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" @close="handleDialogClose">
        <el-form :model="form" :rules="rules" ref="form" label-width="100px">
          <el-form-item label="职位名称" prop="jobName">
            <el-input v-model="form.jobName" placeholder="请输入职位名称"></el-input>
          </el-form-item>
          <el-form-item label="职位类别" prop="categoryId">
            <el-select v-model="form.categoryId" placeholder="请选择职位类别" style="width: 100%">
              <el-option
                v-for="item in categoryOptions"
                :key="item.id"
                :label="item.categoryName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="需求人数" prop="demandNumber">
            <el-input-number v-model="form.demandNumber" :min="1" :max="999" style="width: 100%"></el-input-number>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" v-model="form.remark" :rows="3" placeholder="请输入备注信息"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'JobList',
  data() {
    return {
      loading: false,
      searchForm: {
        jobName: '',
        remark: ''
      },
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      dialogTitle: '新增职位',
      form: {
        id: null,
        jobName: '',
        categoryId: '',
        employerId: '',
        demandNumber: 1,
        hiredNumber: 0,
        remark: ''
      },
      rules: {
        jobName: [
          { required: true, message: '请输入职位名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请选择职位类别', trigger: 'change' }
        ],
        demandNumber: [
          { required: true, message: '请输入需求人数', trigger: 'blur' }
        ]
      },
      categoryOptions: []
    }
  },
  created() {
    this.fetchData()
    this.fetchCategories()
  },
  methods: {
    // 获取职位列表
    async fetchData() {
      this.loading = true
      try {
        const response = await this.$http.post('/job/page1', {
          ...this.searchForm,
          employerId: this.$store.state.user.user.referenceId,
          current: this.currentPage,
          size: this.pageSize
        })
        if (response.data.code === 200) {
          // 转换职位类别ID为名称
          this.tableData = response.data.data.records.map(job => ({
            ...job,
            categoryName: this.getCategoryName(job.categoryId)
          }))
          this.total = response.data.data.total
        }
      } catch (error) {
        console.error('获取职位列表失败:', error)
        this.$message.error('获取职位列表失败')
      } finally {
        this.loading = false
      }
    },
    // 获取职位类别
    async fetchCategories() {
      try {
        const response = await this.$http.get('/job-category/list')
        if (response.data.code === 200) {
          this.categoryOptions = response.data.data
          // 重新获取职位列表以更新类别名称
          await this.fetchData()
        }
      } catch (error) {
        console.error('获取职位类别失败:', error)
        this.$message.error('获取职位类别失败')
      }
    },
    // 根据类别ID获取类别名称
    getCategoryName(categoryId) {
      const category = this.categoryOptions.find(item => item.id === categoryId)
      return category ? category.categoryName : '未知类别'
    },
    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.fetchData()
    },
    // 重置搜索
    resetSearch() {
      this.$refs.searchForm.resetFields()
      this.handleSearch()
    },
    // 新增
    handleAdd() {
      this.dialogTitle = '新增职位'
      this.form = {
        id: null,
        jobName: '',
        categoryId: '',
        employerId: this.$store.state.user.user.referenceId,
        demandNumber: 1,
        hiredNumber: 0,
        remark: ''
      }
      this.dialogVisible = true
    },
    // 编辑
    handleEdit(row) {
      this.dialogTitle = '编辑职位'
      this.form = { ...row }
      this.dialogVisible = true
    },
    // 删除
    handleDelete(row) {
      this.$confirm('确认删除该职位?', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          const response = await this.$http.post('/job/delete?id=' + row.id)
          if (response.data.code === 200) {
            this.$message.success('删除成功')
            this.fetchData()
          }
        } catch (error) {
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      }).catch(() => {})
    },
    // 提交表单
    handleSubmit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            const url = this.form.id ? '/job/update' : '/job/add'
            const response = await this.$http.post(url, this.form)
            if (response.data.code === 200) {
              this.$message.success(this.form.id ? '修改成功' : '新增成功')
              this.dialogVisible = false
              this.fetchData()
            }
          } catch (error) {
            console.error('保存失败:', error)
            this.$message.error('保存失败')
          }
        }
      })
    },
    // 关闭对话框
    handleDialogClose() {
      this.$refs.form.resetFields()
    },
    // 分页大小改变
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchData()
    },
    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },
    // 格式化时间
    formatDateTime(time) {
      if (!time) return ''
      const date = new Date(time)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    }
  }
}
</script>

<style scoped>
.job-list {
  padding: 20px;
}
.search-bar {
  margin-bottom: 20px;
}
.pagination {
  margin-top: 20px;
  text-align: right;
}
</style> 